import numpy as np
import sympy

class HermiteInterpolation:
    def __init__(self, x, y, dy):
        """

        :param x:
        :param y:
        :param dy:
        """
        self.x = np.asarray(x, dtype=np.float)
        self.y = np.asarray(y, dtype=np.float)
        self.dy = np.asarray(dy, dtype=np.float)
        if len(self.x) > 1 and len(self.x) == len(self.y) and len(self.y) == len(self.dy):
            self.n = len(self.x)
        else:
            raise ValueError('插值数据(x, y, dy)维度不匹配！')
        self.polynomial = None
        self.poly_coefficient = None
        self.coefficient_order = None
        self.y0 = None


    def fit_interp(self):
        """
        埃尔米特插值多项式核心算法
        :return:
        """
        t = sympy.Symbol('t')  # 符号变量
        self.polynomial = 0.0  # 初始化

        for i in range(self.n):
            hi, ai = 1.0, 0.0  # 辅助函数构造
            for j in range(self.n):
                if j != i:
                    hi *= ((t - self.x[j]) / (self.x[i] - self.x[j])) ** 2
                    ai += 1 / (self.x[i] - self.x[j])
            self.polynomial += hi * ((self.x[i] - t) * (2 * ai * self.y[i] - self.dy[i]) + self.y[i])

        self.polynomial = sympy.expand(self.polynomial)  # 多项式展开
        polynomial = sympy.Poly(self.polynomial, t)  # 根据多项式构造多项式对象
        self.poly_coefficient = polynomial.coeffs()  # 获取多项式的系数
        self.coefficient_order = polynomial.monoms()  # 多项式系数对应的阶次


